import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Button,
  Row,
  Col,
  Select,
  DatePicker,
  Input,
  Checkbox,
  Form,
  Tabs,
  message,
  InputNumber,
  Modal,
  Upload,
  Space,
} from 'antd';
import { PlusOutlined, ImportOutlined, ExportOutlined, LoadingOutlined, UploadOutlined, EyeOutlined, CloseOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import VendorQuick from '../purchase/vendorQuick';
import moment from 'moment';
import PartQuick from './partQuick';
import UploadUtil from '@/components/UploadUtil';
import ImgQuick from '@/pages/admin/imgQuick';
import CateComp from '@/components/CategoryComponent';
import { EmpSelect, VendorSelect } from '@/components/FormItemSelect';
import request from '@/utils/request';
import PdfReader from '@/components/PdfReader';
import DocHelper from '@/components/DocHelper';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/Part/';
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      loading2: false,
      visible: false,
      visible2: false,
      visible3: false,
      activeKey: '2',
      layout: 'Content',
      record: {
        part: {},
        partRev: {},
      },
      dataSource: [],
      optionPartRev: [],
      fileList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchDatas();
    this.fetchCate();
  }
  onFinish = (values: any) => {
    var part = values.part;
    var partRev = values.partRev;
    this.partEdit(part, partRev);
  };
  partEdit = (part: any, partRev: any) => {
    console.log(part);

    part.pum = part.salesUM = part.ium;
    part.warrantyDate = part.warrantyDate?.format('YYYY-MM-DD');
    this.setState({ loading: true });

    var act = 'Modify';
    if (part.id == 0 || !part.id) {
      act = 'New';
    }
    if (this.state.fileList) {
      var pics: string[] = [];
      this.state.fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      part.ImageFileName = pics.toString();
    } else {
      part.ImageFileName = this.state.datas.ImageFileName;
    }
    if (this.state.drawList) {
      var draws: string[] = [];
      this.state.drawList.forEach((element: any) => {
        draws.push(element.response.result);
      });
      part.DrawFile = draws.toString();
    } else {
      part.DrawFile = this.state.datas?.DrawFile;
    }
    request(apiURL + act, {
      method: 'POST',
      data: part,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success('保存成功！');
          if (part.typeCode == 'M') {
            this.partRevEdit(part, partRev);
          }
          this.fetchDatas();
        }
        this.setState({ loading: false });
      }
    });
  };
  partRevEdit = (part: any, partRev: any) => {
    if (part && partRev) {
      partRev.partNum = part.partNum;
      partRev.revisionNum = partRev.revShortDesc;
      partRev.effictivDate = partRev.effictivDate?.format('YYYY-MM-DD');
      var act = 'Abp/update';
      if (partRev.id == 0 || !partRev.id) {
        act = 'Abp/create';
      }
      this.props
        .dispatch({
          type: act,
          payload: partRev,
          control: 'PartRev',
        })
        .then(() => {
          var resp = this.props.response;
          if (resp.success) {
            if (!resp.result) {
              message.warning('物料版本号有重复！');
            }
          } else {
            message.error('物料版本保存错误，请联系管理员！');
          }
        });
    }
  };
  fetchDatas = () => {
    this.setState({ loading: true });
    this.props
      .dispatch({
        type: 'Abp/getAll',
        payload: { SkipCount: 0, MaxResultCount: 100 },
        control: 'Part',
      })
      .then(() => {
        var resp = this.props.response.result?.items;
        this.setState({
          dataSource: resp,
          loading: false,
        });
      });
  };
  setCurrent = (part?: any, partRev?: any) => {
    this.setState({ activeKey: '1', record: { part, partRev } });
    if (part) {
      if (part.warrantyDate) part.warrantyDate = moment(part.warrantyDate);
      var fileList: any = [];
      if (part.imageFileName) {
        var pics = part.imageFileName.split(',');
        pics.forEach((element: any) => {
          var obj = {
            uid: element,
            name: element,
            response: {
              result: element,
            },
            status: 'done',
            url: UploadUtil.imgServ + element,
          };
          fileList.push(obj);
        });
      }
      this.setState({ fileList });

      var drawList: any = [];
      if (part.drawFile) {
        var items = part.drawFile.split(',');
        items.forEach((element: any) => {
          var obj = {
            uid: element,
            name: element,
            response: {
              result: element,
            },
            status: 'done',
            url: UploadUtil.pdfServ + element,
          };
          drawList.push(obj);
        });
      }
      this.setState({ drawList: drawList.length > 0 ? drawList : undefined, data: part });
      this.formRef.current.setFieldsValue({ part });
      this.fetchRevs(part.partNum);
    }
    setTimeout(() => {
      this.setState({ visible3: false });
    }, 500);
  };
  createNewPart = () => {
    this.setState({ data: null })
    this.formRef.current.setFieldsValue({ part: null });
    this.formRef.current.setFieldsValue({ partRev: null });
  };
  openModal = (record: any, layout: string) => {
    this.setState({ visible: true, disabled: true, record, layout });
  };
  openModal2 = () => {
    this.setState({ visible2: true });
  };
  openModal3 = () => {
    this.setState({ visible3: true });
  };
  closeModal = () => {
    this.setState({ visible: false });
  };
  closeModal2 = () => {
    this.setState({ visible2: false });
  };
  closeModal3 = () => {
    this.setState({ visible3: false });
  };
  fetchCate = () => {
    this.props
      .dispatch({
        type: 'Abp/getTreeList',
        payload: { layout: 'Part-ProdCode' },
        control: 'Category',
      })
      .then(() => {
        this.setState({ optionProdCode: this.props.response.result });
      });
    this.props
      .dispatch({
        type: 'Abp/getTreeList',
        payload: { layout: 'Part-ClassID' },
        control: 'Category',
      })
      .then(() => {
        this.setState({ optionClassID: this.props.response.result });
      });
  };
  fetchRevs = (partNum: string) => {
    this.props
      .dispatch({
        type: 'Abp/getAllByPart',
        payload: { partNum },
        control: 'PartRev',
      })
      .then(() => {
        var items = this.props.response.result;
        this.setState({ optionPartRev: items });
        let partRev = items[0];
        if (partRev) {
          if (partRev.effectiveDate) partRev.effectiveDate = moment(partRev.effectiveDate);
          if (partRev.approvedDate) partRev.approvedDate = moment(partRev.approvedDate);
        }
        this.formRef.current.setFieldsValue({ partRev });
      });
  };
  createNewRev = () => {
    this.formRef.current.setFieldsValue({ partRev: null });
  };
  handleRevChange = (value: any) => {
    const { optionPartRev } = this.state;
    let partRev = optionPartRev.filter((item: any) => item.revisionNum == value)[0];
    if (partRev) {
      if (partRev.effectiveDate) partRev.effectiveDate = moment(partRev.effectiveDate);
      if (partRev.approvedDate) partRev.approvedDate = moment(partRev.approvedDate);
    }
    this.formRef.current.setFieldsValue({ partRev });
  };
  handleUploadList = (info: any) => {
    this.setState({ fileList: info.fileList });
  };
  handleUploadDraw = (info: any) => {
    if (info.file.status === 'done') {
      this.setState({ drawList: info.fileList });
      message.success(`${info.file.name} 上传成功`);
    }
    else if (info.file.status === 'removed') {
      this.setState({ drawList: undefined });
    }
  };
  clickMultiFun = (val: string[]) => {
    let fileList = this.state.fileList;
    val.forEach((element: any) => {
      var obj = {
        uid: element,
        name: element,
        response: {
          result: element,
        },
        status: 'done',
        url: UploadUtil.imgServ + element,
      };
      fileList.push(obj);
    });
    this.setState({ fileList, visible4: false });
  };
  async handlerExport() {
    this.setState({ loading: true });
    var resp = await request('/api/Excel/ExportPart', {
      method: 'POST',
      responseType: 'blob',
    });

    var url = window.URL.createObjectURL(resp);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'part.xls';
    a.click();
    this.setState({ loading: false });
  }
  delObj = () => {
    const { data } = this.state
    let _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        request(apiURL + 'DelPatch', {
          method: 'POST',
          data: [data.id],
        }).then((response) => {
          if (response) {
            if (response.success) {
              _this.formRef.current.resetFields();
            } else {
              message.error(response.error.message);
            }
          }
        });
      },
    });
  }
  handlerImport = (info: any) => {
    if (info.file.status === "done") {
      message.success("导入成功");
      this.setState({ loading2: false })
    }
    else {
      this.setState({ loading2: true })
    }
  };
  doActive = (e: any) => {
    const { data } = this.state;
    if (data.id) {
      request(apiURL + 'DoActive', {
        method: 'POST',
        params: { partNum: data.partNum },
      }).then((response) => {
        if (response.success) {
          this.setCurrent(response.result);
        }
        else{
          this.setCurrent(data);
        }
        
      });
    }
  };
  render() {
    const { record, loading, fileList, drawList, data, loading2 } = this.state;
    const layout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const optionPartRev = this.state.optionPartRev?.map((d: any) => {
      return (
        <Select.Option value={d.revisionNum} key={d.id}>
          {d.revisionNum}
        </Select.Option>
      );
    });
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const disabled = data == null
    return (
      <PageHeaderWrapper title={false}>
        <Form {...layout} ref={this.formRef} onFinish={this.onFinish}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={this.createNewPart}>
              新增
            </Button>
            <Button type="primary" htmlType="submit" disabled={disabled}>
              保存
            </Button>
            <Upload
              accept=".xls,.xlsx,application/vnd.ms-excel"
              name='file'
              action="/api/Excel/ImportPart"
              headers={{
                Authorization: UploadUtil.accessToken,
              }}
              beforeUpload={UploadUtil.checkExcel}
              showUploadList={false}
              onChange={this.handlerImport}
            >
              <Button icon={<ImportOutlined />} loading={loading2}>导入</Button>
            </Upload>
            <Button type="primary" icon={<ExportOutlined />} onClick={()=>this.handlerExport()} loading={loading}>
              导出
            </Button>
            <Button danger icon={<CloseOutlined />} onClick={() => this.delObj()} disabled={disabled}>
              删除
            </Button>
            <DocHelper page="mm734u" />
          </Space>
          <Card style={{ marginTop: 8 }}>
            <Tabs defaultActiveKey="1">
              <TabPane tab="明细" key="1">
                <Row gutter={[16, 16]}>
                  <Col xs={24} sm={24} md={24} lg={15} xl={15}>
                    <Form.Item name={['part', 'id']} style={{ display: 'none' }}>
                      <Input />
                    </Form.Item>
                    <Form.Item label="物料编码" style={{ marginBottom: 0 }}>
                      <Input.Group compact>
                        <Form.Item
                          name={['part', 'partNum']}
                          rules={[{ required: true, message: '物料编码必填' }]}
                        >
                          <Input style={{ width: 138 }} />
                        </Form.Item>
                        <CateComp layout="IUM" width={100} name={['part', 'ium']} required={true} placeholder="单位" />
                        <Form.Item
                          name={['part', 'searchWord']}
                        >
                          <Input placeholder="搜索关键词" style={{ width: 100 }} />
                        </Form.Item>
                        <Form.Item>
                          <Button type="primary" onClick={this.openModal3}>
                            选择
                          </Button>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>

                    <Form.Item
                      name={['part', 'partDescription']}
                      label="物料描述"
                      rules={[{ required: true }]}
                    >
                      <Input.TextArea />
                    </Form.Item>
                    <Form.Item
                      name={['part', 'costMethod']}
                      label="成本方法"
                      rules={[{ required: true }]}
                    >
                      <Select style={{ width: 200 }} placeholder="核算方法">
                        <Select.Option key="A" value="A">
                          平均
                        </Select.Option>
                        <Select.Option key="F" value="F">
                          先进先出
                        </Select.Option>
                        <Select.Option key="L" value="L">
                          最后
                        </Select.Option>
                      </Select>
                    </Form.Item>
                    <Form.Item name={['part', 'typeCode']} label="类型">
                      <Select style={{ width: 200 }} placeholder="请选择类型">
                        <Select.Option value="M">制造</Select.Option>
                        <Select.Option value="P">外购</Select.Option>
                      </Select>
                    </Form.Item>
                    <CateComp
                      layout="Part-ClassID"
                      width={200}
                      name={['part', 'classID']}
                      label="分类"
                    />
                    <CateComp
                      layout="Part-ProdCode"
                      width={200}
                      name={['part', 'prodCode']}
                      label="群组"
                    />
                    <Form.Item name={['part', 'warrantyDate']} label="保修期">
                      <DatePicker />
                    </Form.Item>

                  </Col>
                  <Col xs={24} sm={24} md={24} lg={9} xl={9}>
                    <Form.Item>
                      <Input.Group compact>
                        <Form.Item name={['part', 'inActive']} valuePropName="checked">
                          <Checkbox onChange={(e:any)=>this.doActive(e)}>禁用</Checkbox>
                        </Form.Item>
                        <Form.Item name={['part', 'globalLock']} valuePropName="checked">
                          <Checkbox>全局锁定</Checkbox>
                        </Form.Item>
                        <Form.Item name={['part', 'trackLots']} valuePropName="checked">
                          <Checkbox>批次追踪</Checkbox>
                        </Form.Item>
                        <Form.Item name={['part', 'dropShip']} valuePropName="checked">
                          <Checkbox>直接出货</Checkbox>
                        </Form.Item>
                        <Form.Item name={['part', 'nonStock']} valuePropName="checked">
                          <Checkbox>非库存项目</Checkbox>
                        </Form.Item>
                        <Form.Item name={['part', 'buyToOrder']} valuePropName="checked">
                          <Checkbox>订单式购买</Checkbox>
                        </Form.Item>
                        <Form.Item name={['part', 'noSuggest']} valuePropName="checked">
                          <Checkbox>无需建议</Checkbox>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                    <Form.Item>
                      <Input.Group compact>
                        <Form.Item>
                          <Upload
                            action={UploadUtil.actionURL}
                            headers={{
                              Authorization: UploadUtil.accessToken,
                            }}
                            data={{
                              objectId: record?.part?.id,
                              objectName: 'Part',
                              objectField: 'ImageFileName',
                            }}
                            listType="picture-card"
                            fileList={fileList}
                            multiple={true}
                            onChange={this.handleUploadList}
                          >
                            {fileList.length >= 6 ? null : uploadButton}
                          </Upload>
                        </Form.Item>
                        <Form.Item>
                          <Button onClick={() => this.setState({ visible4: true })}>选择图片</Button>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                    <Form.Item>
                      <Input.Group compact>
                        <Form.Item>
                          <PdfReader url={UploadUtil.pdfServ + record?.part?.drawFile} width={900} text="浏览" icon={<EyeOutlined />} disabled={!record?.part?.drawFile} />
                        </Form.Item>
                        <Form.Item>
                          <Upload
                            action={UploadUtil.actionURL}
                            headers={{
                              Authorization: UploadUtil.accessToken,
                            }}
                            data={{
                              objectId: record?.part?.id,
                              objectName: 'Part',
                              objectField: 'DrawFile',
                            }}
                            fileList={drawList}
                            onChange={this.handleUploadDraw}
                            beforeUpload={UploadUtil.checkPdf}
                          >
                            <Button type="primary" icon={<UploadOutlined />}>图纸上传</Button>
                          </Upload>
                        </Form.Item>
                      </Input.Group>
                    </Form.Item>
                  </Col>
                </Row>
              </TabPane>
              <TabPane tab="MRP属性" key="2">
                <Form.Item name={['part', 'maxnum']} label="最大库存量">
                  <InputNumber />
                </Form.Item>
                <Form.Item name={['part', 'minnum']} label="最小库存量">
                  <InputNumber />
                </Form.Item>
                <Form.Item name={['part', 'saftQty']} label="安全库存">
                  <InputNumber />
                </Form.Item>
                <EmpSelect
                  required={false}
                  width={200}
                  name={['part', 'buyerID']}
                  label="默认采购员"
                />
                <Form.Item name={['part', 'minBuyQty']} label="最少起订量">
                  <InputNumber />
                </Form.Item>
                <Form.Item name={['part', 'preDay']} label="前置时间">
                  <Input suffix="天" style={{ width: 200 }} />
                </Form.Item>
                <VendorSelect
                  required={false}
                  showSearch={true}
                  width={200}
                  name={['part', 'vendorNum']}
                  label="默认供应商"
                />
              </TabPane>
              <TabPane tab="版本" key="3">
                <Form.Item label="版本号" style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['partRev', 'revisionNum']}>
                      <Select
                        style={{ width: 150 }}
                        placeholder="请选择版本"
                        showSearch
                        onChange={this.handleRevChange}
                      >
                        {optionPartRev}
                      </Select>
                    </Form.Item>
                    <Form.Item name={['partRev', 'revShortDesc']}>
                      <Input placeholder="版本缩写" />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item name={['partRev', 'revDescription']} label="版本描述">
                  <Input />
                </Form.Item>

                <Form.Item
                  name={['partRev', 'effectiveDate']}
                  label="生效日期"
                >
                  <DatePicker />
                </Form.Item>
                <Form.Item name={['partRev', 'approved']} label="核准" valuePropName="checked">
                  <Checkbox />
                </Form.Item>
                <Form.Item name={['partRev', 'approvedDate']} label="核准日期">
                  <DatePicker disabled={true} />
                </Form.Item>
                <Form.Item name={['partRev', 'id']} label="ID" style={{ display: 'none' }}>
                  <Input />
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 5 }}>
                  <Button block type="dashed" icon={<PlusOutlined />} onClick={this.createNewRev}>
                    新增版本
                  </Button>
                </Form.Item>
              </TabPane>
              <TabPane tab="替代" key="4">
                <Form.Item name={['part', 'xPartNum']} label="替代物料">
                  <Input style={{ width: 200 }} />
                </Form.Item>
                <Form.Item name={['part', 'xPartDescription']} label="物料描述">
                  <Input.TextArea disabled />
                </Form.Item>
              </TabPane>
              <TabPane tab="其它属性" key="5">
                <Form.Item label="尺寸" style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['part', 'partLength']}>
                      <InputNumber step={0.1} placeholder="长" />
                    </Form.Item>
                    <Form.Item name={['part', 'partWidth']}>
                      <InputNumber step={0.1} placeholder="宽" />
                    </Form.Item>
                    <Form.Item name={['part', 'partHeight']}>
                      <InputNumber step={0.1} placeholder="高" />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
                <Form.Item name={['part', 'diameter']} label="直径">
                  <InputNumber step={0.1} />
                </Form.Item>
                <Form.Item name={['part', 'gravity']} label="重力">
                  <InputNumber step={0.1} />
                </Form.Item>
                <Form.Item name={['part', 'netVolume']} label="净容量">
                  <InputNumber step={0.1} />
                </Form.Item>
                <Form.Item name={['part', 'grossWeight']} label="毛重">
                  <InputNumber step={0.1} />
                </Form.Item>
                <Form.Item name={['part', 'netWeight']} label="净重">
                  <InputNumber step={0.1} />
                </Form.Item>
                <Form.Item
                  name={['part', 'custPartNum']}
                  label="客户物料编码"
                >
                  <Input style={{ width: 200 }} />
                </Form.Item>
                <Form.Item
                  name={['part', 'custPartDesc']}
                  label="客户物料描述"
                >
                  <Input.TextArea style={{ width: 400 }} />
                </Form.Item>
              </TabPane>
            </Tabs>
          </Card>
        </Form>
        <Modal
          title="供应商编辑"
          width={1000}
          visible={this.state.visible2}
          destroyOnClose={true}
          onCancel={this.closeModal2}
          footer={false}
        >
          <VendorQuick />
        </Modal>
        <Modal
          title="物料选择"
          visible={this.state.visible3}
          destroyOnClose={true}
          onCancel={this.closeModal3}
          footer={false}
        >
          <PartQuick setPart={(item: any) => this.setCurrent(item)} inActive={-1} />
        </Modal>
        <Modal
          title="图片选择"
          visible={this.state.visible4}
          destroyOnClose={true}
          onCancel={() => this.setState({ visible4: false })}
          width={750}
          footer={false}
        >
          <ImgQuick clickMultiFun={(val: any) => this.clickMultiFun(val)} ext='.jpg,.jpeg,.png,.gif' />
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
